<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card class="box-card">
      <div>
        <el-alert
          title="注意：只允许为第三级分类设置相关参数"
          type="warning"
          show-icon
        >
        </el-alert>
      </div>
      <div class="block">
        选择商品分类：
        <el-cascader
          v-model="selectParams"
          :options="popupReceiveProductList"
          :props="configurationInformation"
          @change="setParamsList"
        ></el-cascader>
      </div>
      <el-tabs v-model="activeName" @tab-click="handleClickParams">
        <el-tab-pane label="动态参数" name="first">
          <el-button
            type="primary"
            round
            :disabled="buttonVisible"
            @click="dialogVisible = true"
            >添加参数</el-button
          >
          <el-table :data="ParamsArguments" style="width: 100%" border>
            <el-table-column type="expand" label="" width="180">
              <template slot-scope="scope">
                <el-tag
                  closable
                  v-for="(item, index) in scope.row.attr_vals"
                  :key="index"
                  @close="handleClose(index, scope.row.attr_vals)"
                >
                  {{ item }}
                </el-tag>
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="putInputConfirm(scope.row)"
                  @blur="scope.row.inputVisible = false"
                >
                </el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="handleInputConfirm(scope.row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <el-table-column type="index" label="#"> </el-table-column>
            <el-table-column prop="attr_name" label="参数名称">
            </el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button type="primary" round>修改</el-button>
                <el-button
                  type="warning"
                  round
                  @click="clearTableConfirm(scope.row)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="静态属性" name="second">
          <el-button
            type="primary"
            round
            :disabled="buttonVisible"
            @click="dialogVisible = true"
            >添加参数</el-button
          >
          <el-table :data="ParamsArguments" style="width: 100%" border>
            <el-table-column type="expand" label="">
              <template slot-scope="scope">
                <el-tag
                  closable
                  v-for="(item, index) in scope.row.attr_vals"
                  :key="index"
                  @close="handleClose(index, scope.row.attr_vals)"
                >
                  {{ item }}
                </el-tag>
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="putInputConfirm(scope.row)"
                  @blur="scope.row.inputVisible = false"
                >
                </el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="handleInputConfirm(scope.row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <el-table-column type="index" label="#"> </el-table-column>
            <el-table-column prop="attr_name" label="参数名称">
            </el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button type="primary" round icon="el-icon-edit"
                  >修改</el-button
                >
                <el-button
                  type="danger"
                  round
                  icon="el-icon-delete"
                  @click="clearTableConfirm(scope.row)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
      <!-- 添加参数 弹出表单 -->
      <el-dialog
        title="提示"
        :visible.sync="dialogVisible"
        width="50%"
        @close="closepostButtonConfirm"
      >
        <el-form
          ref="formRules"
          label-width="auto"
          :model="putParams"
          :rules="putParamsRules"
        >
          <el-form-item label="添加参数名称:" prop="attr_name">
            <el-input
              v-model="putParams.attr_name"
              placeholder="请输入内容"
            ></el-input>
          </el-form-item>
          <el-form-item label="添加参数属性:">
            <el-input
              v-model="putParams.attr_vals"
              placeholder="请输入内容"
            ></el-input>
          </el-form-item>
        </el-form>

        <span slot="footer" class="dialog-footer">
          <el-button @click="closepostButtonConfirm">取 消</el-button>
          <el-button type="primary" @click="postButtonConfirm">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
export default {
  data() {
    return {
      // 级联选择器渲染参数
      configurationInformation: {
        expandTrigger: "hover",
        label: "cat_name",
        value: "cat_id",
        children: "children",
      },
      // 级联选择器获取数据参数
      productList: {
        type: 3,
        pagenum: 1,
        pagesize: 5,
      },
      // 级联选择器列表
      popupReceiveProductList: [],
      // 获取的参数列表数据
      ParamsArguments: [],
      // 选中的商品分类
      selectParams: [],
      // 选中选项卡类名
      activeName: "first",
      // 添加商品按钮控制
      buttonVisible: true,
      //添加商品输入框控制
      dialogVisible: false,
      putParams: {
        attr_name: "",
        attr_vals: "",
      },
      putParamsRules: {
        attr_name: [
          { required: true, message: "请输入参数名称", trigger: "blur" },
          {
            min: 1,
            max: 15,
            message: "长度在 1 到 15 个字符",
            trigger: "blur",
          },
        ],
      },
    };
  },
  methods: {
    //获取全部分类列表
    async getProductList() {
      const { data: res } = await this.$http({
        url: "/categories",
        method: "get",
        params: {
          ...this.productList,
        },
      });
      this.popupReceiveProductList = res.data.result;
    },
    // 获取分类参数列表
    async getParamsList() {
      const { data: res } = await this.$http({
        url: `categories/${
          this.selectParams[this.selectParams.length - 1]
        }/attributes`,
        method: "get",
        params: {
          sel: this.activeName == "first" ? "many" : "only",
        },
      });
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
      this.ParamsArguments = res.data;
      this.buttonVisible = false;
      this.ParamsArguments.forEach((item) => {
        item.attr_vals = item.attr_vals ? item.attr_vals.split(",") : [];
        // 动态添加控制按钮的属性
        this.$set(item, "inputVisible", false);
        this.$set(item, "inputValue", "");
      });
    },
    // 获取选中分类参数列表
    setParamsList() {
      if (this.selectParams.length !== 3) {
        this.selectParams = [];
        this.ParamsArguments = [];
        return;
      }
      this.getParamsList();
    },
    // 获取对应选项卡分类参数列表
    handleClickParams() {
      if (this.selectParams.length !== 3) return;
      this.getParamsList();
    },
    // 打开并选中当前选项卡的添加参数输入框
    handleInputConfirm(row) {
      this.$set(row, "inputVisible", true);
      this.$nextTick((_) => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },
    // 关闭输入框并发送添加的参数的属性
    async putInputConfirm(row) {
      if (row.inputValue.trim().length !== 0) {
        row.attr_vals.push(row.inputValue.trim());
        this.putConfirm(row);
      } else {
        return this.$message.error("输入不能为空");
      }
      row.inputVisible = false;
    },
    // 发送添加的参数的属性
    async putConfirm(row) {
      const { data: res } = await this.$http({
        url: `categories/${row.cat_id}/attributes/${row.attr_id}`,
        method: "put",
        data: {
          attr_name: row.attr_name,
          attr_sel: row.attr_sel,
          attr_vals: row.attr_vals.toString(),
        },
      });
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
      this.$message.success(res.meta.msg);
    },
    // 删除选中参数标签
    handleClose(index, row) {
      row.splice(index, 1);
      this.putConfirm(row);
    },

    // 添加新的参数
    postButtonConfirm() {
      this.$refs.formRules.validate(async (valid) => {
        if (!valid) return;
        const { data: res } = await this.$http({
          url: `categories/${
            this.selectParams[this.selectParams.length - 1]
          }/attributes`,
          method: "post",
          data: {
            ...this.putParams,
            attr_sel: this.activeName == "first" ? "many" : "only",
          },
        });
        if (res.meta.status !== 201) return this.$message.error(res.meta.msg);
        this.dialogVisible = false;
        this.setParamsList();
        this.closepostButtonConfirm();
        this.$message.success(res.meta.msg);
      });
    },
    //关闭添加参数弹框
    closepostButtonConfirm() {
      this.$refs.formRules.resetFields();
      this.dialogVisible = false;
      this.putParams = { attr_name: "", attr_vals: "" };
    },
    // 删除当前参数
    async clearTableConfirm(val) {
      const result = await this.$confirm(
        "此操作将永久删除该参数, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err) => err);
      if (result !== "confirm") return this.$message.error("已取消删除");
      const { data: res } = await this.$http({
        url: `categories/${val.cat_id}/attributes/${val.attr_id}`,
        method: "delete",
      });
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
      this.$message.success(res.meta.msg);
      this.setParamsList();
    },
  },
  created() {
    // 获取全部分类列表
    this.getProductList();
  },
};
</script>

<style lang="less" scoped>
.el-tag + .el-tag {
  margin-left: 10px;
}
.button-new-tag {
  margin-left: 10px;
  width: 91px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}
.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}
.el-button {
  margin: 15px 10px;
}
</style>
